const mongoose = require('mongoose');
const crypto = require('crypto');
const xss = require('xss');
const User = require('../models/user');
const Chat = require('../models/chat');
const Friend = require('../models/friend');
const Group = require('../models/group');
const { getJwt, testJwt } = require('../utils');

// xss是一个用于对用户输入的内容进行过滤，以避免遭受 XSS 攻击的模块

// 登录
exports.login = async (ctx, next) => {
    const fields = ctx.request.fields;
    const name = xss(fields.name).trim();
    const password = xss(fields.password).trim();
    const md5 = crypto.createHash('md5');
    const endpaw = md5.update(password).digest('hex'); // 密码加密
    if (!name || !password) {
        ctx.body = {
            message: '参数不能为空',
            reasonCode: 404
        }
    } else {
        await new Promise((resolve, reject) => {
            User.findOne({name}, function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    const token = getJwt({name, password: endpaw});
                    if (!data) { // 如果此用户不存在，就注册一个
                        let user = new User({name, password: endpaw, online: true});
                        user.save(function(err, data) {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(token);
                            }
                        })
                    } else {                       
                        if (data.password === endpaw) {
                            User.findOneAndUpdate({name}, {online: true}, function(err, data) {
                                if (err) {
                                    reject(err);
                                } else {
                                    resolve(token);
                                }
                            })
                        } else {
                            resolve(false);
                        }
                    }
                }
            })
        }).then(data => {
            if (data) {
                ctx.body = {
                    reasonCode: 200,
                    message: '登录成功',
                    token: data
                }
            } else {
                ctx.body = {
                    reasonCode: 404,
                    message: '密码错误'
                }
            }
        }).catch(err => {
            ctx.body = err;
        })
    }
    
}

// 获取登录用户信息
exports.get = async (ctx, next) => {
    // 根据token查用户信息
    const token = ctx.request.headers['x-access-token'];
    if (token) {
        try {
            const decoded = testJwt(token);
            const name = decoded.name;
            const password = decoded.password;
            const user = await User.findOne({ name });
                   
            if (!user) {
                ctx.body = {
                    reasonCode: 404,
                    message: '用户不存在'
                }
            } else {
                user.last_login_time = Date.now();
                await user.save();
                const newToken = getJwt({name, password});
                const friends = await Friend.find({'$or': [{ from: user._id }, { to: user._id }]}).populate('to from', {
                    avatar: 1, name: 1
                });
                console.log(friends);
                const groups = await Group.find({members: user._id}); 
                ctx.body = {
                    reasonCode: 200,
                    user: {
                        name: name,
                        id: user._id,
                        friends,
                        groups 
                    },
                    token: newToken
                }
            }
                      
        } catch(err) {
            // 登录过期
            ctx.body = {
                reasonCode: 302,
                message: '登录过期'
            }
        }
    } else {
        // 未登录
        ctx.body = {
            reasonCode: 302,
            message: '请先登录'
        }
    }
}

// 获取用户列表
exports.list = async (ctx, next) => {
    const { name } = ctx.request.query;
    await new Promise((resolve, reject) => {
        User.find({name: {$regex: name}}, function(err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        })
    }).then(data => {
        ctx.body = {
            reasonCode: 200,
            users: data
        }
    }).catch(err => {
        ctx.body = err;
    })
}




